/*
 *  This program is free software; you can redistribute it and/or modify
 *  it under the terms of the GNU Lesser General Public License Version
 *  3 as published by the Free Software Foundation.
 *
 *  This program is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU Lesser General Public License for more details.
 *
 *  You should have received a copy of the GNU Lesser General Public
 *  License along with this program; if not, write to the Free Software
 *  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307,
 *  USA.
 */


#include "connector.h"

Connector::Connector(QObject *parent) :
        QObject(parent)
{
    client = new QTcpSocket(this);
    connect(client, SIGNAL(connected()), this, SLOT(connected()));
    connect(client, SIGNAL(disconnected()), this, SLOT(disconnected()));
    connect(client, SIGNAL(error(QAbstractSocket::SocketError)),this, SLOT(displayError(QAbstractSocket::SocketError)));
    connect(client, SIGNAL(readyRead()), this, SLOT(readyRead()));
}

Connector::~Connector()
{
    client->abort();
    client->close();
}

void Connector::readyRead()
{
    QTcpSocket *c = (QTcpSocket*)sender();
    if (!c->isValid())
        return;

    QByteArray arr = c->readAll();
    QTextStream qout(stdout, QFile::WriteOnly);
    QString ret = QString::fromUtf8(arr);
    qout << QString("%1\n\r").arg(ret);

    emit result(arr);
}


bool Connector::send(const QString& command)
{
    if (!client->isWritable())
        return false;

    client->write(command.toUtf8());
    client->waitForBytesWritten();
    client->flush();
    client->waitForReadyRead();
    return true;
}

void Connector::connected()
{
    emit ready();
}

void Connector::disconnected()
{
    //exit(0);
    //qDebug() << "Disconnected.";
}

bool Connector::connectOptra(const QString& host, qint16 port)
{
    client->abort();
    client->connectToHost(host, port);
    if (!client->waitForConnected(3000)){
        return false;
    }

    return true;
}

void Connector::displayError(QAbstractSocket::SocketError socketError)
{
    QString er;
    QTextStream qout(&er, QFile::WriteOnly);

    switch (socketError) {
    case QAbstractSocket::RemoteHostClosedError:
        break;
    case QAbstractSocket::HostNotFoundError:
        qout << "The host was not found. Please check the host name and port settings.";
        break;
    case QAbstractSocket::ConnectionRefusedError:
        qout << "The connection was refused by the peer. "
                <<  "Make sure the server is running, "
                <<  "and check that the host name and port "
                <<  "settings are correct.";
        break;
    default:
        qout << QString("The following error occurred: %1.").arg(client->errorString());
    }

    emit error(er);
}
